package com.qf.controller;

import com.qf.pojo.Shop;
import com.qf.service.ShopService;
import com.qf.utils.QiNiuYunUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author 高圆圆
 * @date 2023/2/6 16:28
 * 针对商品的控制器层
 */
@Controller
@RequestMapping("/shop")
public class ShopController {

    //注入商品业务接口
    @Autowired
    private ShopService shopService ;

    //springmvc的restful
    @RequestMapping("/findAll") //@GetMapping 等价于@RequestMapping("/xx",method=RequestMethod.GET)
    public String findAll(Model model){
        List<Shop> list = shopService.getShops();

        if(list!=null){
            model.addAttribute("list",list) ;
        }
        return  "shop_list";
    }


    /**
     * 查询指定的商品
     * @param id 商品id
     * @return
     */
    @RequestMapping("/findById/{shopId}")
    public String getShop(@PathVariable("shopId") String id,Model model ){

        System.out.println(id);
        //String---int
        int shopId = Integer.parseInt(id);

        Shop shop = shopService.getShopById(shopId);
        if(shop!=null){
            //将shop存储在模型组件中
            model.addAttribute("shop",shop) ;
            return "shop" ;
        }else{
            return "fail";
        }

    }


    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String updateShop(Shop shop, @RequestParam("file")MultipartFile multipartFile) throws IOException {
        System.out.println(shop) ;

        System.out.println(multipartFile.getInputStream());
        String imgUrl = QiNiuYunUploadUtils.updateUtils(multipartFile);
        //封装图片地址
        shop.setPimg(imgUrl);

        int count = shopService.updateShop(shop);
        if(count>0){
            return "redirect:/shop/findAll" ;
        }else{
            return  "fail" ;
        }

    }

    @RequestMapping("/del")
    public String delShop(@RequestParam("ids") String id){

        System.out.println(id) ;
        int shopId = Integer.parseInt(id) ;
        int count = shopService.delShop(shopId);
        if(count>0){
            return "redirect:/shop/findAll" ;
        }else{
            return  "fail" ;
        }

    }

}
